let stream;
document.querySelector("#toupin").onclick = async () => {
  stream = await navigator.mediaDevices.getDisplayMedia({
    video: true, // 请求视频轨道
    audio: true, // 请求音频轨道
  });
  console.log(".then ~ stream:", stream);
  // 将获取的流绑定到video元素上
  const videoElement = document.querySelector("#videoElement");
  videoElement.srcObject = stream;
  // 添加监听器以处理流结束的情况
  stream.onend = () => {
    videoElement.srcObject = null;
    console.log("Stream ended");
  };
  stream.onaddtrack = (event) => {
    console.log("新轨道添加：", event.track);
    // 你可以在这里执行更多操作，比如处理新添加的轨道
  };
  stream.onremovetrack = (event) => {
    console.log("轨道被移除：", event.track);
    // 你可以在这里执行更多操作，比如处理轨道被移除的逻辑
  };
};

document.querySelector("#toupinclose").onclick = async () => {
  if (stream) {
    // 停止媒体流中的每个轨道
    stream.getTracks().forEach((track) => {
      track.stop();
    });

    // 从视频元素中移除媒体流
    const videoElement = document.querySelector("#videoElement");
    if (videoElement) {
      videoElement.srcObject = null;
    }

    // 将 stream 设置为 null，表示屏幕共享已关闭
    stream = null;
  }
};

var video = document.getElementById("videoElement");
video.addEventListener("loadedmetadata", function () {
  const videoWidth = video.videoWidth;
  const videoHeight = video.videoHeight;
  console.log("videoHeight:", videoHeight);
  console.log("videoWidth:", videoWidth);
  const width = video.width;
  const height = width * (videoHeight / videoWidth);
  const ratio = videoWidth / width;
  console.log("Video width:", width, "Video height:", height);
  var canvas = document.createElement("canvas");
  canvas.id = "canvasElement";
  canvas.width = width;
  canvas.height = height;
  canvas.style.position = "absolute";
  canvas.style.top = "50%";
  canvas.style.left = "50%";
  canvas.style.transform = "translate(-50%, -50%)";
  video.parentNode.appendChild(canvas);
  var ctx = canvas.getContext("2d");
  // 设置线型为虚线
  // ctx.setLineDash([5, 5]); // 画5个单位的线，空15个单位，如此循环
  const rect = {
    startX: 200,
    startY: 100,
    width: 100,
    height: 100,
    scale: 1,
    scaleArea: "",
    mouseXFromStart: 0, // 鼠标距离左上角x距离
    mouseYFromStart: 0, // 鼠标距离左上角y距离
  };
  const drawRect = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
    ctx.beginPath();
    ctx.strokeStyle = "#00a1ff";
    ctx.strokeRect(rect.startX, rect.startY, rect.width, rect.height);
    ctx.fillStyle = "#00a1ff";
    ctx.fillRect(rect.startX - 5, rect.startY - 5, 10, 10);
    ctx.fillRect(rect.startX + rect.width - 5, rect.startY - 5, 10, 10);
    ctx.fillRect(rect.startX - 5, rect.startY + rect.height - 5, 10, 10);
    ctx.fillRect(
      rect.startX + rect.width - 5,
      rect.startY + rect.height - 5,
      10,
      10
    );
  };
  drawRect();

  var isScaling = false;
  var dragging = false;

  // var startX,
  //   startY,
  //   endX,
  //   endY,
  //   isScaling = false;

  // ctx.drawImage(video, 0, 0, width, height);
  // requestAnimationFrame(() => {
  //   ctx.drawImage(video, 0, 0, width, height);
  // });

  canvas.addEventListener(
    "mousedown",
    function (e) {
      // 鼠标按下事件
      var rectX = rect.startX;
      var rectY = rect.startY;
      var endX = e.offsetX;
      var endY = e.offsetY;
      if (
        endX >= rectX &&
        endX <= rectX + rect.width &&
        endY >= rectY &&
        endY <= rectY + rect.height
      ) {
        dragging = true;
        rect.mouseXFromStart = endX - rect.startX;
        rect.mouseYFromStart = endY - rect.startY;
      } else {
        dragging = false;
      }
      // 点击左上角
      if (
        e.offsetX >= rectX - 5 &&
        e.offsetX <= rectX + 5 &&
        e.offsetY >= rectY - 5 &&
        e.offsetY <= rectY + 5
      ) {
        console.log("左上角点击");
        isScaling = true;
        rect.scaleArea = "TL";
      }
      // 点击右上角
      if (
        e.offsetX >= rectX + rect.width - 5 &&
        e.offsetX <= rectX + rect.width + 5 &&
        e.offsetY >= rectY - 5 &&
        e.offsetY <= rectY + 5
      ) {
        console.log("右上角点击");
        isScaling = true;
        rect.scaleArea = "TR";
      }
      // 点击左下角
      if (
        e.offsetX >= rectX - 5 &&
        e.offsetX <= rectX + 5 &&
        e.offsetY >= rectY + rect.height - 5 &&
        e.offsetY <= rectY + rect.height + 5
      ) {
        console.log("左下角点击");
        isScaling = true;
        rect.scaleArea = "BL";
      }
      // 点击右下角
      if (
        e.offsetX >= rectX + rect.width - 5 &&
        e.offsetX <= rectX + rect.width + 5 &&
        e.offsetY >= rectY + rect.height - 5 &&
        e.offsetY <= rectY + rect.height + 5
      ) {
        console.log("右下角点击");
        isScaling = true;
        rect.scaleArea = "BR";
      }
    },
    false
  );

  canvas.addEventListener(
    "mousemove",
    function (e) {
      var rectX = rect.startX;
      var rectY = rect.startY;
      var endX = e.offsetX;
      var endY = e.offsetY;
      if (
        endX >= rectX &&
        endX <= rectX + rect.width &&
        endY >= rectY &&
        endY <= rectY + rect.height
      ) {
        canvas.style.cursor = "move";
      } else {
        canvas.style.cursor = "default";
      }
      // 点击左上角
      if (
        e.offsetX >= rectX - 5 &&
        e.offsetX <= rectX + 5 &&
        e.offsetY >= rectY - 5 &&
        e.offsetY <= rectY + 5
      ) {
        canvas.style.cursor = "nw-resize";
      }
      // 点击右上角
      if (
        e.offsetX >= rectX + rect.width - 5 &&
        e.offsetX <= rectX + rect.width + 5 &&
        e.offsetY >= rectY - 5 &&
        e.offsetY <= rectY + 5
      ) {
        canvas.style.cursor = "ne-resize";
      }
      // 点击左下角
      if (
        e.offsetX >= rectX - 5 &&
        e.offsetX <= rectX + 5 &&
        e.offsetY >= rectY + rect.height - 5 &&
        e.offsetY <= rectY + rect.height + 5
      ) {
        canvas.style.cursor = "ne-resize";
      }
      // 点击右下角
      if (
        e.offsetX >= rectX + rect.width - 5 &&
        e.offsetX <= rectX + rect.width + 5 &&
        e.offsetY >= rectY + rect.height - 5 &&
        e.offsetY <= rectY + rect.height + 5
      ) {
        canvas.style.cursor = "nw-resize";
      }
      if (isScaling) {
        // 检查鼠标点击是否在缩放手柄上
        // var startX = e.offsetX;
        // var startY = e.offsetY;
        // var deltaX = e.offsetX - startX;
        // var deltaY = e.offsetY - startY;
        // var aspectRatio = rect.originalWidth / rect.originalHeight;

        // // 计算新的宽度和高度
        // var newWidth = rect.width + deltaX;
        // var newHeight = rect.height + deltaY;
        // var scale = Math.min(
        //   newWidth / rect.originalWidth,
        //   newHeight / rect.originalHeight,
        //   2
        // ); // 限制最大缩放比例为2

        // // 保持宽高比
        // if (newWidth / newHeight > aspectRatio) {
        //   newWidth = newHeight * aspectRatio;
        // } else {
        //   newHeight = newWidth / aspectRatio;
        // }
        if (rect.scaleArea === "TL") {
          rect.startX = endX;
          rect.startY = endY;
          rect.width = rectX + rect.width - endX;
          rect.height = rectY + rect.height - endY;
        }
        if (rect.scaleArea === "TR") {
          rect.startY = endY;
          rect.width = endX - rect.startX;
          rect.height = rectY + rect.height - endY;
        }
        if (rect.scaleArea === "BL") {
          rect.width = rectX + rect.width - endX;
          rect.height = endY - rectY;
          rect.startX = endX;
        }
        if (rect.scaleArea === "BR") {
          rect.width = endX - rectX;
          rect.height = endY - rectY;
        }

        // 更新画布
        drawRect();
      }
      if (dragging) {
        rect.startX = endX - rect.mouseXFromStart;
        rect.startY = endY - rect.mouseYFromStart;
        drawRect();
      }
      // if (isScaling) {
      //   endX = e.offsetX;
      //   endY = e.offsetY;
      //   ctx.clearRect(0, 0, canvas.width, canvas.height);
      //   ctx.strokeStyle = "red";
      //   // 设置线型为虚线
      //   // ctx.setLineDash([5, 5]); // 画5个单位的线，空15个单位，如此循环
      //   ctx.strokeRect(startX, startY, endX - startX, endY - startY);
      // }
    },
    false
  );

  // 鼠标松开事件
  canvas.addEventListener(
    "mouseup",
    function () {
      // canvas.removeEventListener("mousemove", onMouseMove);
      // canvas.removeEventListener("mouseup", arguments.callee);
      isScaling = false;
      dragging = false;
    },
    false
  );

  const cut = ({ startX, startY, cropWidth, cropHeight }) => {
    // Create a new canvas for the cropped image
    var _canvas = document.createElement("canvas");
    _canvas.width = cropWidth;
    _canvas.height = cropHeight;

    // 绘制裁切图片
    var canvasCtx = _canvas.getContext("2d");
    console.log(
      "startX, startY, cropWidth, cropHeight",
      startX,
      startY,
      cropWidth,
      cropHeight
    );
    canvasCtx.drawImage(
      video,
      startX * ratio,
      startY * ratio,
      cropWidth * ratio,
      cropHeight * ratio,
      0,
      0,
      cropWidth,
      cropHeight
    );

    // Display the cropped image
    var canvasDataUrl = _canvas.toDataURL();
    return canvasDataUrl;
  };
  document.querySelector("#jiepin").onclick = () => {
    const dataUrl1 = cut({
      startX: rect.startX,
      startY: rect.startY,
      cropWidth: rect.width,
      cropHeight: rect.height,
    });
    document.querySelector("#img1").src = dataUrl1;
    setTimeout(() => {
      const dataUrl2 = cut({
        startX: rect.startX,
        startY: rect.startY,
        cropWidth: rect.width,
        cropHeight: rect.height,
      });
      document.querySelector("#img2").src = dataUrl2;
      console.log("图片是否相同", dataUrl1 === dataUrl2);
    }, 3000);
  };

  // canvas.addEventListener(
  //   "mouseup",
  //   function () {
  //     // if (isScaling) {
  //     //   isScaling = false;
  //     //   var cropWidth = endX - startX;
  //     //   var cropHeight = endY - startY;
  //     //   const dataUrl1 = cut({ startX, startY, cropWidth, cropHeight });
  //     //   document.querySelector("#img1").src = dataUrl1;
  //     //   setTimeout(() => {
  //     //     const dataUrl2 = cut({ startX, startY, cropWidth, cropHeight });
  //     //     document.querySelector("#img2").src = dataUrl2;
  //     //     console.log("图片是否相同", dataUrl1 === dataUrl2);
  //     //   }, 3000);
  //     // }
  //   },
  //   false
  // );
});

// document.body.onclick = (e) => {
//   console.log("x", e.offsetX, e.offsetY);
// };

function canvasToBlob(canvas, callback) {
  canvas.toBlob(function (blob) {
    callback(blob);
  }, "image/png");
}

function blobToArrayBuffer(blob, callback) {
  const reader = new FileReader();
  reader.readAsArrayBuffer(blob);
  reader.onload = function () {
    callback(reader.result);
  };
}

function compareArrayBuffers(buffer1, buffer2) {
  if (buffer1.byteLength !== buffer2.byteLength) {
    return false;
  }
  const uint8Arr1 = new Uint8Array(buffer1);
  const uint8Arr2 = new Uint8Array(buffer2);
  for (let i = 0; i < uint8Arr1.length; i++) {
    if (uint8Arr1[i] !== uint8Arr2[i]) {
      return false;
    }
  }
  return true;
}

// canvasToBlob(canvas1, (blob1) => {
//   blobToArrayBuffer(blob1, (arrayBuffer1) => {
//     const canvas2 = document.createElement("canvas");
//     canvas2.width = cropWidth;
//     canvas2.height = cropHeight;
//     var ctx2 = canvas2.getContext("2d");
//     ctx2.drawImage(
//       video,
//       x,
//       y,
//       cropWidth,
//       cropHeight,
//       0,
//       0,
//       cropWidth,
//       cropHeight
//     );
//     var canvas2DataUrl = canvas2.toDataURL();
//     console.log("canvas2DataUrl", canvas2DataUrl); // You can use this URL to display or download the cropped image
//     const img2 = document.querySelector("#img2");
//     img2.src = canvas2DataUrl;
//     canvasToBlob(canvas2, (blob2) => {
//       blobToArrayBuffer(blob2, (arrayBuffer2) => {
//         const areSame = compareArrayBuffers(
//           arrayBuffer1,
//           arrayBuffer2
//         );
//         console.log("两张图片是否相同:", areSame);
//       });
//     });
//   });
// });
